package cn.hxzy.ownerSource.service.impl;

import cn.hxzy.common.Result;
import cn.hxzy.common.util.RandomId;
import cn.hxzy.entity.order.vo.SelectVo;
import cn.hxzy.entity.siteEntity.Site;
import cn.hxzy.entity.sourceEntity.SourceList;
import cn.hxzy.entity.sourceEntity.SourceOperation;
import cn.hxzy.ownerSource.clients.BankAccountClient;
import cn.hxzy.ownerSource.clients.SiteClient;
import cn.hxzy.ownerSource.mapper.SourceListMapper;
//import cn.hxzy.ownerSource.quartz.job.StartSourceJob;
import cn.hxzy.ownerSource.mapper.SourceOperationMapper;
import cn.hxzy.ownerSource.service.SourceListService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.seata.spring.annotation.GlobalTransactional;
//import org.quartz.JobExecutionContext;
//import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ao.Li
 * @since 2023-06-23
 */
@Service
public class SourceListServiceImpl extends ServiceImpl<SourceListMapper, SourceList> implements SourceListService {

    @Autowired
    private SourceListMapper sourceListMapper;

    @Autowired
    private SiteClient siteClient;
    @Autowired
   private RedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private BankAccountClient bankAccountClient;

    @Autowired
    private SourceOperationMapper operationMapper;



    /**
     * 新增货源
     *
     * @param sourceList
     * @return
     */
    //开启全局事务
    @GlobalTransactional
    @Override
    public SourceList addSource(SourceList sourceList, String userId, int pwd, Double money) {
        Result result = bankAccountClient.selectById(userId, pwd, money);
        Boolean aBoolean = objectMapper.convertValue(result.getData1(), Boolean.class);

        //没有执行成功，结束操作
        if (!aBoolean) {
            return null;
        }

//设置用户id货源id
        sourceList.setUserId(userId);
        sourceList.setSourceId(RandomId.getSourceId());
        int flag = sourceListMapper.insert(sourceList);

        //新增货源日志
        SourceOperation operation = new SourceOperation();
        operation.setOperationId(RandomId.getOperateId());
        operation.setSourceId(sourceList.getSourceId());
        operation.setOperationTime(new Date());
        operation.setOperationType(102);
        operation.setRemark("发布货源");
        int i = operationMapper.insert(operation);

        if (flag > 0 && i > 0) {
            return sourceList;
        }
        return null;
    }

    /**
     * 根据货源编号查找货源对象
     *
     * @param sourceId
     * @return
     */
    @Override
    public SourceList selectSourceById(String sourceId) {
        QueryWrapper<SourceList> wrapper = new QueryWrapper<>();
        wrapper.eq("source_id", sourceId);
        SourceList source = sourceListMapper.selectOne(wrapper);

        //根据货源发货站点id查询发货站点对象
        Result result = siteClient.selectById(source.getLoadingSiteId());
        Site loadingSite = objectMapper.convertValue(result.getData1(), Site.class);
        source.setLoadingSite(loadingSite);
        //根据货源收货站点id查询收货站点对象
        Result unResult = siteClient.selectById(source.getUnloadingSiteId());
        Site unloadingSite = objectMapper.convertValue(unResult.getData1(), Site.class);
        source.setUnloadingSite(unloadingSite);

        if (source != null) {
            redisTemplate.opsForValue().set("source",source);
            return source;
        }
       return null;
    }

    /**
     * 查询开启状态的所有货源
     *
     * @return
     */
    @Override
    public List<SourceList> isSourceListOn(String userId, Integer sourceStatus) {
        QueryWrapper<SourceList> wrapper = new QueryWrapper<>();
        wrapper.eq("source_status", sourceStatus);
        wrapper.eq("user_id", userId);
        wrapper.orderByDesc("posts_time");
        List<SourceList> sourceLists = sourceListMapper.selectList(wrapper);
        for (SourceList source : sourceLists) {
            //根据货源发货站点id查询发货站点对象
            Result result = siteClient.selectById(source.getLoadingSiteId());
            Site loadingSite = objectMapper.convertValue(result.getData1(), Site.class);
            source.setLoadingSite(loadingSite);
//            //根据货源收货站点id查询收货站点对象
            Result unResult = siteClient.selectById(source.getUnloadingSiteId());
            Site unloadingSite = objectMapper.convertValue(unResult.getData1(), Site.class);
            source.setUnloadingSite(unloadingSite);

        }

        return sourceLists;
    }

    /**
     * 自动
     *
     * @param jobExecutionContext
     * @param sourceId
     * @return
     */
//    @Override
//    public Boolean startSource(JobExecutionContext jobExecutionContext,String sourceId) {
//        SourceList sourceList = new SourceList();
//        sourceList.setSourceStatus(106);
//        int i = sourceListMapper.updateById(sourceList);
//        if (i>0){
//            return true;
//        }
//       return false;
//    }


    /**
     * 生成4位随机数
     *
     * @return
     */
    public static String getFourRandom() {
        Random random = new Random();
        String fourRandom = random.nextInt(10000) + "";
        int randLength = fourRandom.length();
        if (randLength < 4) {
            for (int i = 1; i <= 4 - randLength; i++)
                fourRandom = "0" + fourRandom;
        }
        return fourRandom;
    }

    /**
     * 查询所有货源列表
     * @return
     */
    @Override
    public Result selectSource() {
        QueryWrapper<SourceList> sourceListQueryWrapper = new QueryWrapper<>();
        List<SourceList> sourceLists = sourceListMapper.selectList(sourceListQueryWrapper);
        for (SourceList source : sourceLists) {
            //根据货源发货站点id查询发货站点对象
            Result result = siteClient.selectById(source.getLoadingSiteId());
            Site loadingSite = objectMapper.convertValue(result.getData1(), Site.class);
            source.setLoadingSite(loadingSite);
            //根据货源收货站点id查询收货站点对象
            Result unResult = siteClient.selectById(source.getUnloadingSiteId());
            Site unloadingSite = objectMapper.convertValue(unResult.getData1(), Site.class);
            source.setUnloadingSite(unloadingSite);
        }
        if (sourceLists!=null)return Result.ok().data("sourceLists",sourceLists);
        return Result.error().message("查询失败！");
    }
    /**
     * 查询所有货源列表
     * @return
     */
    @Override
    public Result selectSourceByStatus() {
        QueryWrapper<SourceList> sourceListQueryWrapper = new QueryWrapper<>();
        sourceListQueryWrapper.eq("source_status",106);
        List<SourceList> sourceLists = sourceListMapper.selectList(sourceListQueryWrapper);
        for (SourceList source : sourceLists) {
            //根据货源发货站点id查询发货站点对象
            Result result = siteClient.selectById(source.getLoadingSiteId());
            Site loadingSite = objectMapper.convertValue(result.getData1(), Site.class);
            source.setLoadingSite(loadingSite);
            //根据货源收货站点id查询收货站点对象
            Result unResult = siteClient.selectById(source.getUnloadingSiteId());
            Site unloadingSite = objectMapper.convertValue(unResult.getData1(), Site.class);
            source.setUnloadingSite(unloadingSite);
        }
        if (sourceLists!=null)return Result.ok().data("sourceLists",sourceLists);
        return Result.error().message("查询失败！");
    }

    /**
     *    修改装货量
     * @param loadingCount
     * @param sourceId
     * @return
     */
    @Override
    public Result updateLoadingCount(Double loadingCount,String sourceId) {
        UpdateWrapper<SourceList> sourceWrapper = new UpdateWrapper<>();
        sourceWrapper.eq("source_id",sourceId);
        SourceList sourceList = new SourceList();
        sourceList.setLoadingCount(loadingCount);
        int update = sourceListMapper.update(sourceList, sourceWrapper);
        if (update>0)return Result.ok().message("修改成功！");

        return Result.error().message("修改失败！");
    }

    /**
     * 根据货源站点编号多条件查询货源
     */
    @Override
    public Result selectMoreByTj(String loading, String unLoading, int i) {
        QueryWrapper<SourceList> sourceListQueryWrapper = new QueryWrapper<>();
        if (loading!=null){
            sourceListQueryWrapper.eq("loading_site_id",loading);
        }
        if (unLoading!=null){
            sourceListQueryWrapper.eq("unloading_site_id",unLoading);
        }
        if (i==1){
            sourceListQueryWrapper.orderByDesc("source_freight");
        }
        List<SourceList> sourceLists = sourceListMapper.selectList(sourceListQueryWrapper);
        for (SourceList source : sourceLists) {
            //根据货源发货站点id查询发货站点对象
            Result result = siteClient.selectById(source.getLoadingSiteId());
            Site loadingSite = objectMapper.convertValue(result.getData1(), Site.class);
            source.setLoadingSite(loadingSite);
            //根据货源收货站点id查询收货站点对象
            Result unResult = siteClient.selectById(source.getUnloadingSiteId());
            Site unloadingSite = objectMapper.convertValue(unResult.getData1(), Site.class);
            source.setUnloadingSite(unloadingSite);
        }
        if (sourceLists!=null)return Result.ok().data("sourceLists",sourceLists);
        return Result.error().message("查询失败！");
    }
    /**
     * 根据货源站点城市名称多条件查询货源
     */
    @Override
    public Result selectMoreBySiteName(SelectVo selectVo) throws JsonProcessingException {
        int i = selectVo.getI();
        ArrayList<Site> data1 = new ArrayList<>();
        ArrayList<Site> data2 = new ArrayList<>();
        if (!selectVo.getLoading().equals("无")){
            String loadingName = selectVo.getLoading();
            Result result1 = siteClient.selectByName(loadingName);
            data1 =(ArrayList<Site>) result1.getData1();
        }
        if (!selectVo.getUnLoading().equals("无")){
            String unLoadingName = selectVo.getUnLoading();
            Result result2 = siteClient.selectByNameUn(unLoadingName);
            data2 =(ArrayList<Site>) result2.getData1();
        }
        List<Site> sites = new ArrayList<Site>();
        List<Site> sites1 = new ArrayList<Site>();
        if (!selectVo.getLoading().equals("无")){
            String s2 = objectMapper.writeValueAsString(data1);
             sites = objectMapper.readValue(s2, new TypeReference<List<Site>>() {
                @Override
                public Type getType() {
                    return super.getType();
                }
            });
        }
        if (!selectVo.getUnLoading().equals("无")){
            String s3 = objectMapper.writeValueAsString(data2);
             sites1 = objectMapper.readValue(s3, new TypeReference<List<Site>>() {
                @Override
                public Type getType() {
                    return super.getType();
                }
            });
        }
        System.out.println("sites"+sites);
        System.out.println("data2"+sites1);
        //装车地点有数值，卸车地点有或无数值
        ArrayList<List<SourceList>> objects = new ArrayList<>();
        if (!selectVo.getLoading().equals("无")){
            for (Site site : sites) {
//                System.out.println("data1"+site.getClass());
//                QueryWrapper<SourceList> sourceListQueryWrapper = new QueryWrapper<>();
//                sourceListQueryWrapper.eq("loading_site_id",site.getId());
                if (!selectVo.getUnLoading().equals("无")){
                    for (Site site1 : sites1) {
//                        sourceListQueryWrapper.eq("unloading_site_id",site1.getId());
//                        List<SourceList> sourceLists = sourceListMapper.selectList(sourceListQueryWrapper);
                        List<SourceList> sourceLists = sourceListMapper.selectByLoadingAndUn(site.getId(), site1.getId());
                        objects.add(sourceLists);
                    }
                }
                List<SourceList> sourceLists = sourceListMapper.selectByLoading(site.getId());
                objects.add(sourceLists);
            }
        }
        if (selectVo.getLoading().equals("无")){
            if (!selectVo.getUnLoading().equals("无")){
                for (Site site1 : sites1) {
//                    QueryWrapper<SourceList> sourceListQueryWrapper = new QueryWrapper<>();
//                    sourceListQueryWrapper.eq("unloading_site_id",site1.getId());
                    List<SourceList> sourceLists = sourceListMapper.selectByUnLoading(site1.getId());
                    // List<SourceList> sourceLists = sourceListMapper.selectList(sourceListQueryWrapper);
                    objects.add(sourceLists);
                }
            }
        }
//        ArrayList<SourceList> sourceLists1 = new ArrayList<>();
//        for (int i1 = 0; i1 < objects.size(); i1++) {
//            for (int i2 = 0; i2 < objects.get(i1).size(); i2++) {
//                sourceLists1.add(objects.get(i1).get(i2));
//            }
//        }
        List<SourceList> collect=new ArrayList<>();
        for (List<SourceList> object : objects) {
            for (SourceList sourceList : object) {
                collect.add(sourceList);
            }
        }
        if (i==1){
            collect = collect.stream().sorted((o1, o2) -> o2.getSourceFreight().intValue() - o1.getSourceFreight().intValue()).collect(Collectors.toList());
        }
        for (SourceList sourceList : collect) {
            //根据货源发货站点id查询发货站点对象
            Result result = siteClient.selectById(sourceList.getLoadingSiteId());
            Site loadingSite = objectMapper.convertValue(result.getData1(), Site.class);
            sourceList.setLoadingSite(loadingSite);
            //根据货源收货站点id查询收货站点对象
            Result unResult = siteClient.selectById(sourceList.getUnloadingSiteId());
            Site unloadingSite = objectMapper.convertValue(unResult.getData1(), Site.class);
            sourceList.setUnloadingSite(unloadingSite);
        }
        return Result.ok().data1(collect);
    }
    /**
     * 修改卸货量
     * @param unloadingCount
     * @return
     */
    @Override
    public Result updateUnloadingCount(Double unloadingCount,String sourceId) {
        UpdateWrapper<SourceList> sourceWrapper = new UpdateWrapper<>();
        sourceWrapper.eq("source_id",sourceId);
        SourceList sourceList = new SourceList();
        sourceList.setUnloadingCount(unloadingCount);
        int update = sourceListMapper.update(sourceList, sourceWrapper);
        if (update>0)return Result.ok().message("修改成功！");

        return Result.error().message("修改失败！");
    }

    /**
     * 修改货物余量
     * @param goodsHeadroom
     * @return
     */
    @Override
    public Result updateGoodsHeadroom(Double goodsHeadroom,String sourceId) {
        UpdateWrapper<SourceList> sourceWrapper = new UpdateWrapper<>();
        sourceWrapper.eq("source_id",sourceId);
        SourceList sourceList = new SourceList();
        sourceList.setGoodsHeadroom(goodsHeadroom);
        int update = sourceListMapper.update(sourceList, sourceWrapper);
        if (update>0)return Result.ok().message("修改成功！");

        return Result.error().message("修改失败！");
    }

    /**
     * 修改货源状态
     * @param status
     * @return
     */
    @Override
    public Boolean updateSourceStatus(String sourceId,Integer status) {
        UpdateWrapper<SourceList> wrapper = new UpdateWrapper<>();
        wrapper.eq("source_id",sourceId);
        //查找到这个货源对象
        SourceList source = sourceListMapper.selectOne(wrapper);
        //修改它的状态
        source.setSourceStatus(status);
        int flag = sourceListMapper.update(source, wrapper);

        //新增货源操作日志
        SourceOperation operation = new SourceOperation();
        operation.setOperationId(RandomId.getOperateId());
        operation.setOperationTime(new Date());
        if (status == 103) {
            operation.setOperationType(101);
            operation.setRemark("暂停货源");
        } else if(status == 102) {
            operation.setOperationType(103);
            operation.setRemark("关闭货源");
        }

        //插入数据
        int i = operationMapper.insert(operation);
        if (flag > 0 && i > 0) return true;
        return false;
    }
}

